package com.msmall.community.common.listener;

import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.msmall.base.util.Constants;
import com.msmall.base.util.StringUtil;
import com.msmall.community.ApplicationManager;
import com.msmall.community.common.OnlineUser;
import com.msmall.community.user.service.UserManager;


public class OnlineUserListener implements HttpSessionListener {
	
	private final Log log = LogFactory.getLog(OnlineUserListener.class);
	
	public void sessionCreated(HttpSessionEvent hse) {
		HttpSession session = hse.getSession();
		Long userid = null;
		String username = "";
		do {
			userid = StringUtil.randomLong(7);
        } while (OnlineUser.getOnlineUsers().get(userid) != null);
		username = Constants.USER_ANONYMOUS + StringUtil.randomString(5);
		
		UserManager userManager = (UserManager) ApplicationManager.appContext.getBean("userManager");
		userManager.createAnonymousAccount(userid, username);
		OnlineUser.anonymousCreated(userid, session);
	}
	
	public void sessionDestroyed(HttpSessionEvent hse) {
		HttpSession session = hse.getSession();
		Long userid = (Long)session.getAttribute(Constants.SESSION_USER_ID_KEY);
		int role = OnlineUser.getOnlineUsers().get(userid).getRole();
		if(role == OnlineUser.USER_ROLE_ANONYMOUS){
			OnlineUser.anonymousLogout(userid);
			UserManager userManager = (UserManager) ApplicationManager.appContext.getBean("userManager");
			userManager.removeAnonymousAccount(userid);
		}else if(role == OnlineUser.USER_ROLE_ADMIN){
			OnlineUser.adminLogout(userid);
		}else{
			// 刷新用户到数据库  退出时不刷新
			UserManager userManager = (UserManager) ApplicationManager.appContext.getBean("userManager");
			userManager.updateLogoutInfo(userid);
			OnlineUser.userLogout(userid);
		}
	}
}
